package me.zhengjie.logging.domain

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.bean.copier.CopyOptions
import com.fasterxml.jackson.annotation.JsonTypeName
import me.zhengjie.common.utils.JacksonUtil
import jakarta.persistence.*
import org.hibernate.annotations.CreationTimestamp
import org.springframework.data.redis.core.RedisHash
import java.sql.Timestamp

/**
 * @author Kuki Wu
 * @date 2024-11-24
 */
@Entity
@Table(name = "sys_log")
@JsonTypeName("SysLog")
@RedisHash("syslog")
data class SysLog(
    @Id
    @Column(name = "log_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,

    // 操作用户
    var username: String? = null,

    // 描述
    var description: String? = null,

    // 方法名
    var method: String? = null,

    // 参数
    @Column(columnDefinition = "text")
    var params: String? = null,

    // 日志类型
    @Column(name = "log_type")
    var logType: String? = null,

    // 请求ip
    @Column(name = "request_ip")
    var requestIp: String? = null,

    @Column(name = "address")
    var address: String? = null,

    var browser: String? = null,

    // 请求耗时
    var time: Long? = null,

    // 异常详细
    @Column(name = "exception_detail", columnDefinition = "text")
    var exceptionDetail: ByteArray = ByteArray(0),

    // 创建日期
    @CreationTimestamp
    @Column(name = "create_time")
    var createTime: Timestamp? = null
){
    constructor(logType: String, time: Long?):this(){
        this.logType = logType
        this.time = time
    }
    annotation class Update

    companion object {
        fun fromJson(json: String): SysLog? {
            val obj=JacksonUtil.parseObject(json, SysLog::class.java)!!
            return when(obj){
                is SysLog -> obj
                else -> null
            }
        }
    }

    fun tojson():String? {
        return JacksonUtil.toJSONString(this)
    }

    fun copy(source: SysLog?) {
        BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true))
    }
}